<?php

namespace App\Logging;

use Monolog\Logger;

class SingleLogger
{
    /**
     * Create a custom Monolog instance.
     *
     * @param  array  $config
     * @return \Monolog\Logger
     */
    public function __invoke(array $config)
    {
        $handlers = [];
        $levels = ['debug', 'info', 'error', 'alert'];
        $fileInfo = pathinfo($config['path']);
        foreach ($levels as $l) {
            $path = $fileInfo['dirname'] . '/' . $fileInfo['filename'] . "-$l." . $fileInfo['extension'];
            if ($l == 'alert'){
                $path = $fileInfo['dirname'] . '/exception.' .$fileInfo['extension'];
            }
            $h = new SingleHandler(
                $path,
                $config['days'] ?? 7,
                $l,
                $config['bubble'] ?? true,
                $config['permission'] ?? null,
                $config['locking'] ?? false
            );
            $h->setFormatter(new LineFormatter(null, null, true, true));
            $handlers[] = $h;
        }
        return new Logger($this->parseChannel($config), $handlers);
    }

    /**
     * Extract the log channel from the given configuration.
     *
     * @param  array  $config
     * @return string
     */
    protected function parseChannel(array $config)
    {
        if (!isset($config['name'])) {
            return app()->bound('env') ? app()->environment() : 'production';
        }

        return $config['name'];
    }
}